<template>
    <!-- 题库管理 -->
    <div class="question">
        <!-- xs、sm、md、lg 和 xl。 -->
        <el-row :gutter="15">
            <el-col class="categorys" :sm="12" :md="4" :lg="4">
                <p class="title">分类列表</p>
                <el-button
                    type="primary"
                    icon="el-icon-plus"
                    @click="newDialogFormVisible=true"
                >新增分类</el-button>
                <el-button
                    type="danger"
                    icon="el-icon-delete-solid"
                    plain
                    @click="delCategory"
                    :disabled="$refs.categoryTree && $refs.categoryTree.getCheckedKeys().length<1"
                >删除分类</el-button>
                <el-input placeholder="搜索分类" v-model="search">
                    <el-button slot="append" icon="el-icon-search" ></el-button>
                </el-input>
                <!-- <el-menu>
					<el-menu-item
						v-for="category in categorys"
						:key="category.id"
						@click="categoryClick(category)"
						contextmenu="showMenu"
					>
						<i class="el-icon-folder"></i>
						<span>{{category.name}}</span>
					</el-menu-item>
                </el-menu>-->

                <el-tree
                    class="filter-tree"
                    :data="categorys"
                    :props="defaultProps"
                    @node-click="categoryClick"
                    show-checkbox
                    default-expand-all
                    node-key="id"
                    :filter-node-method="filterNode"
                    ref="categoryTree"
                ></el-tree>
            </el-col>
            <el-col class="list" :sm="24" :md="18" :lg="20">
                <p class="title">试题列表</p>
                <el-button-group>
                    <el-button
                        icon="el-icon-plus"
                        type="primary"
                        @click="$router.push({path: '/question/add'})"
                    >新增试题</el-button>
                    <!-- <el-button icon="el-icon-upload">导入试题</el-button> -->
                    <Excel></Excel>
                    <el-input placeholder="输入题目标题搜索试题" v-model="listSearch">
                        <el-button slot="append" icon="el-icon-search"></el-button>
                    </el-input>
                    <el-button icon="el-icon-delete-solid">删除试题</el-button>
                </el-button-group>
                
                <div class="pull-right">
                    <span class="margin-right">试题类型:</span>
                    <el-select v-model="dataForm.testType">
                       <el-option
                            v-for="(value, key) in testType"
                            :key="key"
                            :value="key"
                            :label="value"
                        ></el-option>
                    </el-select>
                </div>

                <!-- 表格 -->
                <el-table :data="tableData" style="width:100%" border v-loading="dataListLoading">
                    <template slot="empty">
                        <div>
                            <b>
                                <i>{{ activeCategoryName }}</i>
                            </b>
                            &nbsp;这个分类的
                            <b>
                                <i>{{ testType[dataForm.testType] }}</i>
                            </b>
                            &nbsp;还没有试题
                        </div>
                    </template>
                    <!-- 选择框  -->
                    <el-table-column type="selection" width="40"></el-table-column>
                    <el-table-column type="index" column-key="index"></el-table-column>
                    <el-table-column
                        prop="qstStem"
                        label="试题标题"
                        sortable
                        :show-overflow-tooltip="true"
                        header-align="center"
                        align="center"
                    >
                        <template slot-scope="scope">
                            <p v-html="delHtmlTag(scope.row.qstStem)"></p>
                        </template>
                    </el-table-column>
                    <el-table-column
                        prop="difficult"
                        label="试题难度"
                        width="100"
                        :filters="[{ text: '简单', value: 1 }, { text: '一般', value: 2 }, { text: '困难', value:3}]"
                        :filter-method="filterdifficult"
                        filter-placement="bottom-end"
                    >
                        <template slot-scope="scope">
                            <el-tag
                                :type="scope.row.difficult === 1 ? 'primary' : ((scope.row.difficult === 2) ? 'success' :  'info')"
                                disable-transitions
                            >{{difficultLabel[scope.row.difficult - 1]}}</el-tag>
                        </template>
                    </el-table-column>

                    <el-table-column prop="teacherName" label="教师" sortable width="72"></el-table-column>
                    <!-- <el-table-column prop="category" label="试题分类" sortable width="100"></el-table-column> -->
                    <!-- <el-table-column
                        prop="type"
                        label="题型"
                        width="72"
                        :filters="[{ text: '单选题', value: '单选题' }, { text: '多选题', value: '多选题' }, { text: '简答题', value: '简答题'}, { text: '判断题', value: '判断题'}]"
                        :filter-method="filterType"
                    ></el-table-column>-->
                    <el-table-column prop="score" label="分数" sortable width="70"></el-table-column>
                    <el-table-column label="操作" width="165" header-align="center">
                        <template slot-scope="scope">
                            <el-button
                                title="编辑"
                                type="primary"
                                plain
                                @click="handleEdit(scope.$index, scope.row)"
                            >
                                <i class="el-icon-edit"></i>
                            </el-button>
                            <el-popover
                                :width="500"
                                style="margin:0 5px; "
                                placement="top-end"
                                title="详细内容"
                                trigger="click"
                            >
                                <TestDeatil :test="scope.row"/>
                                <el-button slot="reference" type="primary" plain title="查看">
                                    <i class="el-icon-view"></i>
                                </el-button>
                            </el-popover>
                            <el-button
                                title="删除"
                                type="danger"
                                plain
                                @click="handleDelete(scope.$index, scope.row)"
                            >
                                <i class="el-icon-delete"></i>
                            </el-button>

                          
                        </template>
                    </el-table-column>
                </el-table>

                <el-pagination
                    @size-change="sizeChangeHandle"
                    @current-change="currentChangeHandle"
                    :current-page="pageIndex"
                    :page-sizes="[10, 20, 40, 70, 100]"
                    :page-size="pageSize"
                    :total="totalPage"
                    layout="total, sizes, prev, pager, next, jumper"
                ></el-pagination>
            </el-col>
        </el-row>

        <!-- 新增科目分类对话框 -->
        <el-dialog
            class="dialog"
            title="新增分类"
            :visible.sync="newDialogFormVisible"
            style="max-width:800px; margin:0 auto;"
        >
            <el-select v-model="courseId" size="media">
                <el-option
                    v-for="item in categorys"
                    :key="item.id"
                    :value="item.id"
                    :label="item.name"
                ></el-option>
            </el-select>
            <el-input
                v-model="newCategoryName"
                autocomplete="off"
                placeholder="输入分类名称"
                size="media"
            ></el-input>
            <el-button @click="newDialogFormVisible = false" size="small">取 消</el-button>
            <el-button type="primary" @click="newCategory" size="small">确 定</el-button>
        </el-dialog>
    </div>
</template>

<script>
import TestDeatil from "@/components/test-detail";
import Excel from "./excel"
export default {
    components: { TestDeatil, Excel },
    data() {
        return {
            search: "",
            listSearch: "",
            loading: true, // 加载中
            categorys: [],
            pecialty: "", // 专业id
            courseId: "", // 新建科目名
            newCategoryName: "",
            newDialogFormVisible: false,
            tableData: [],
            difficultLabel: ["简单", "一般", "困难"],
            defaultProps: {
                children: "children",
                label: "name"
            },
            dataForm: {
                selectCategoryId: "", //选中的分类id
                testType: "qst_single_view" // 选中的试题类型
            },
            activeCategoryName: '',
            totalPage: 0,
            pageIndex: 1,
            pageSize: 10,
            testType: {
                qst_single_view: "单项选择题",
                qst_more_view: "多项选择题",
                qst_judge: "判断题",
                qst_gap_fillging: "填空题",
                qst_design: "问答题"
            },
            dataListLoading: false
        };
    },
    async created() {
        await this.getCategoryList();

    },
    watch: {
        search(val) {
            this.$refs.categoryTree.filter(val);
        },
        "dataForm.testType": function() {
            this.pageIndex = 1;
            this.getTest();
        }
    },
    methods: {
        // 每页数
        sizeChangeHandle(val) {
            this.pageSize = val;
            this.pageIndex = 1;
            this.getTest();
        },
        // 当前页
        currentChangeHandle(val) {
            this.pageIndex = val;
            this.getTest();
        },
        // 去掉html标签
        delHtmlTag(str) {
            return str.replace(/<[^>]+>/g, "");
        },
        getCategoryList() {
            this.$http("/api/getcourselist").then(res => {
                console.log("res.data", res.data);
                this.categorys = res.data;
                this.courseId = res.data[0].id;
                this.pecialty = res.data[0].pecialty;
                this.dataForm.selectCategoryId = res.data[0].children[0].id;
                this.activeCategoryName = res.data[0].children[0].name;
                this.getTest();
            }).catch(() => {
                this.$message.error('加载失败， 请重试');
            })
        },
        filterNode(value, data) {
            if (!value) return true;
            return data.name.toLowerCase().includes(value.toLowerCase());
        },
        // 新增分类
        newCategory() {
            // console.log('asdk')
            let { courseId, pecialty, newCategoryName } = this;
            if (courseId) {
                this.$http("/api/newcourse", {
                    params: {
                        courseId,
                        pecialty,
                        newCategoryName
                    }
                }).then(res => {
                    if (res.data.code === 0) {
                        this.newDialogFormVisible = false;
                        // this.categorys.push(res.data.data)
                        this.getCategoryList();
                        this.$message(res.data.msg);
                    }
                });
            } else {
                this.$message.error("课程名不能为空");
            }
        },
        //   分类点击
        categoryClick(currObj, currNode, vueComponent) {
            console.log('currObj', currObj)
            if (currNode.isLeaf) {
                this.dataForm.selectCategoryId = currObj.id;
                this.activeCategoryName = currObj.name;
                this.getTest();
            }
        },
        // 得到试题
        getTest() {
            if (!this.dataForm.selectCategoryId) return;
            if (this.dataListLoading) return;
            this.dataListLoading = true;
            this.$http("/api/question/list", {
                params: {
                    categoryId: this.dataForm.selectCategoryId,
                    tName: this.dataForm.testType,
                    page: this.pageIndex,
                    limit: this.pageSize
                }
            })
                .then(({ data }) => {
                    console.log("data", data);
                    this.tableData = [];
                    if (data.code === 0) {
                        this.tableData = data.page.list;
                        this.totalPage = data.page.totalCount;
                    } else {
                        this.tableData = [];
                        this.totalPage = 0;
                    }
                    this.dataListLoading = false;
                })
                .catch(() => {
                    this.$message.error('加载失败， 请稍后重试');
                    this.dataListLoading = false;
                });
        },
        handleEdit(index, row) {
            console.log("index, row", index, row);
        },
        handleDelete(index, row) {
            console.log("index, row", index, row);
        },
        filterdifficult(value, row) {
            return row.difficult === value;
        },
        filterType(value, row) {
            return row.type === value;
        },

        showMenu(parameter) {
            parameter.preventDefault();
            var x = parameter.clientX;
            var y = parameter.clientY;
            console.log("asdkfljal;");
            this.entityTreeContextMenu.axios = { x, y };
        },
        // 删除分类
        delCategory() {
            if (this.$refs.categoryTree.getCheckedKeys().length < 1) {
                this.$message("请选择分类");
                return false;
            }
            this.$confirm("此操作将永久删除该分类, 是否继续?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(() => {
                // console.log('this.$refs.categoryTree.getCheckedKeys()', this.$refs.categoryTree.getCheckedKeys())
                console.log(
                    "this.$refs.categoryTree",
                    this.$refs.categoryTree.getCheckedNodes()
                );
                let arr = this.$refs.categoryTree.getCheckedNodes();
                let data = [];
                arr.map(item => {
                    // 没有孩子
                    if (!item.children) {
                        console.log("item", item);
                        data.push(item.id + "");
                    }
                });
                console.log("data", data);
                this.$http("/api/category/del", {
                    params: {
                        data: data
                    }
                }).then(res => {
                    this.getCategoryList();
                    this.$message(res.data.msg);
                });
            });
        }
    }
};
</script>

<style lang="scss" >
.title {
    font-size: 14px;
    font-weight: bold;
    padding: 5px 0;
}
.categorys {
    .el-button {
        // padding: 6px 15px;
        // width: 100%;
        // border-radius: 0%;
        margin: 5px 0;
    }
    .el-input {
        margin: 5px;
    }
    .el-menu {
        .el-menu-item {
            height: 25px;
            line-height: 25px;
            i {
                color: #dfba49;
            }
        }
    }
}
.list {
    .el-button-group {
        .el-input,
        > .el-button {
            padding-top: 6px;
            padding-bottom: 6px;
            margin: 0 2px;
        }
        .el-input {
            width: 200px;
            padding-top: 0;
            > .el-input-group__append,
            > .el-input__inner {
                height: 28px;
            }
        }
    }
}
</style>

<style lang="scss">
.question {
    // padding: 5px 20px;
    // padding-bottom: 100px;
    .list {
        .el-button-group {
            .el-input {
                > .el-input-group__append,
                > .el-input__inner {
                    height: 28px;
                }
            }
        }
    }
    .dialog .el-dialog__body {
        text-align: right;
        .el-input {
            padding: 10px;
        }
    }
    // 选中的树节点
    .el-tree-node.is-expanded.is-current {
        // background: #f4f4f5;
        background: #cae4ff;
        // padding-left: 0;
        // margin-left: 18px;
    }
    .el-table__body .el-table__row {
        height: 40px;
        overflow: hidden;
    }
}
</style>